package com.apes.framework.plugin.fsm.schedule;

import com.apes.framework.api.DomainService;
import com.apes.framework.plugin.esb.api.SimpleRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @Title: WorkScheduleService
 * @Description: 排班
 * @author: ZhengZeXian
 * @create: 2021/1/11 15:56
 */
@Service("fsmWorkScheduleService")
public class WorkScheduleService extends DomainService {

    @Autowired
    WorkScheduleRepository workScheduleRepository;

    /**
     * 保存
     * @param request
     * @return
     */
    public WorkSchedule save(SimpleRequest request){
        WorkSchedule workSchedule = request.getO(WorkSchedule.class);
        workSchedule = workScheduleRepository.saveAndFlush(workSchedule);
        return workSchedule;
    }

    /**
     * 修改
     * @param request
     * @return
     */
    public WorkSchedule update(SimpleRequest request){
        checkData(request);
        WorkSchedule workSchedule = request.getO(WorkSchedule.class);
        workSchedule = workScheduleRepository.saveAndFlush(workSchedule);
        return workSchedule;
    }

    /**
     * 删除
     * @param request
     * @return
     */
    public String delete(SimpleRequest request) {
        checkData(request);
        String id = request.get("id");
        workScheduleRepository.delete(id);
        return "删除成功";
    }

    /**
     * 检查数据
     * @param request
     */
    public void checkData(SimpleRequest request){
        String id = request.get("id");
        long versions = (int) request.get("version"); // 获取当前请求的版本信息
        WorkSchedule workSchedule = workScheduleRepository.findOne(id);
        if (workSchedule == null) throw new RuntimeException("排班【" + id + "】在系统中不存在。");
        if(workSchedule.getVersion() != versions) throw new RuntimeException("记录已更新或已删除，请重新提交！");  // 用于判断当前版本是否被修改
    }
}
